/**
 * 实现哈希表 --- 哈希桶
 */
public class HashBuck {
    public static final double DEFAULT_LOAD_FACTOR = 0.75;
    // 节点
    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;

    public HashBuck() {
        this.array = new Node[10];
    }
    // 尾插法插入元素
    public void put(int key,int val){
        int index = hash(key);
        Node cur = array[index];
        Node prev = null;
        while (cur != null){
            if (cur.key == key){
                cur.val = val;
                return;
            }
            prev = cur;
            cur = cur.next;
        }
        Node next = new Node(key,val);
        if (prev == null){
            array[index] = next;
        }else{
            prev.next = next;
        }
        usedSize++;

        // 插入元素成功后，检查当前散列表的负载因子
        if (loadFactor() >= DEFAULT_LOAD_FACTOR){
            // 负载因子大于等于规定的，就需要扩容
            array = resize();
        }
    }
    // 当负载因子大了，就扩容
    // 如果扩容了，则 每个元素应该重新 hash到哈希表中
    public Node[] resize(){
        Node[] newArray = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                int index = cur.key % newArray.length;
                // 保存cur后面的节点，防止被丢掉
                Node curNext = cur.next;
                // 把 cur节点插入到新数组对应下标 -- 头插法
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        return newArray;
    }
    // 求负载因子
    public double loadFactor(){
        return 1.0*usedSize/array.length;
    }
    // 获取元素
    public int get(int key){
        int index = hash(key);
        Node cur = array[index];
        while (cur != null){
            if (cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
    public int hash(int key){
        return key % 10;
    }
}
